package com.monster.util;

import com.monster.dao.BaseDao;

import java.sql.SQLException;

/**
 * 分页功能工具类，用于分页时的页数获取
 * @author cyb
 */
public class PageUtil extends BaseDao {
    /**
     * 执行的sql语句，通过对该sql语句的改造可以获得总页数
     */
    public static String sql = "";
    public static Object[] params =null;
    /**
     * 根据sql语句和每页个数获取需要查询的数据的总页数
     * @param perCount 每页数量
     * @return 总页数
     */
    public static int getTotalPage(int perCount) {
        sql = sql.toLowerCase();
        int beginIndex = sql.indexOf("from");
        int lastIndex = sql.indexOf("order by");
        sql = "SELECT COUNT(1) " + sql.substring(beginIndex, lastIndex);
        int totalPage = 0;
        rs = executeQuery(sql,params);
        try {
            while (rs.next()) {
                int result = rs.getInt(1);
                totalPage = result % perCount == 0 ? result / perCount : result / perCount + 1;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return totalPage;
    }
}